<template>
  <div class="app-container">


      <el-form
        ref="form"
        class="common-form"
        :model="form"
        label-width="100px"
        :inline-message="true"
        style='height:600px;overflow:auto;'
      >


      <el-button type="primary" :disabled='detail.seat_generat_status != 0' @click.native="insertTopic()" style='margin-bottom:20px;'>新增科目</el-button>


      <el-card class="box-card"  v-for="(block, index) in form.topicinfo" :key="index">
        <div slot="header" class="clearfix">
          <span>科目设置</span>
          <i  v-if='index != 0 && detail.seat_generat_status ==0' style="float: right; padding: 3px 0;cursor:pointer;"  @click="delTopic(index)" class="el-icon-delete"></i>
        </div>
        <div>
          <el-row >
            <el-col :span="7">
              <el-form-item  label="科目" style='width:100%;'>
                <el-select v-model="block.id" placeholder="请选择">
                   <el-option
                     v-for="item in topicList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
                   </el-option>
                 </el-select>
              </el-form-item>
            </el-col>
           <el-col :span="6">
              <!-- <el-form-item  label='分批次'>
                 <el-radio v-model="block.changci" label="0">关闭</el-radio>
                <el-radio v-model="block.changci" label="1">开启</el-radio>
              </el-form-item> -->
              <el-button type="primary" :disabled='detail.seat_generat_status != 0' @click.native="insertChangci(index)" style='margin-bottom:20px;margin-left: 20px;'>新增考试批次</el-button>

            </el-col>
          </el-row>



        </div>
        <div  v-if='block.changci == 0'>
          <el-row >
            <el-col :span="8">
              <el-form-item  label='考试日期'>
                <el-date-picker
                  v-model="block.date"
                  value-format='yyyy-MM-dd'
                  type="date"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item  label='开始时间'>
                <el-time-select
                  v-model="block.start_time"
                  :picker-options="{start: '07:00',step: '00:15',end: '18:30'}"
                  placeholder="开始时间">
                </el-time-select>
              </el-form-item>
              <el-form-item  label='结束时间'>
                <el-time-select
                  v-model="block.end_time"
                  :picker-options="{start: '07:00',step: '00:15',end: '18:30'}"
                  placeholder="开始时间">
                </el-time-select>
              </el-form-item>
            </el-col>

          </el-row>
        </div>
        <div  v-if='block.changci == 1'>
          <div class='changci' v-for="(changci_item, sub_index) in block.list" :key="sub_index">
            <div class='changci-del' v-if='sub_index != 0 && detail.seat_generat_status ==0'>
              <i style="cursor:pointer;color:#fff;"  @click="delChangci(index,sub_index)" class="el-icon-close"></i>
            </div>
            <el-row  >
              <el-col :span="12">
                <el-form-item  label="名称">
                  <el-input v-model="changci_item.name" placeholder="请输入内容"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row  >
              <el-col :span="12">
                <el-form-item  label="考试人数">
                  <el-input v-model="changci_item.people"  type='number' placeholder="请输入考试人数"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item  label='考试日期'>
                  <el-date-picker
                    v-model="changci_item.date"
                    value-format='yyyy-MM-dd'
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row  >
              <el-col :span="12">
                <el-form-item  label='开始时间'>
                  <el-time-select
                    v-model="changci_item.start_time"
                    :picker-options="{start: '07:00',step: '00:15',end: '18:30'}"
                    placeholder="开始时间">
                  </el-time-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item  label='结束时间'>
                  <el-time-select
                    v-model="changci_item.end_time"
                    :picker-options="{start: '07:00',step: '00:15',end: '18:30'}"
                    placeholder="开始时间">
                  </el-time-select>
                </el-form-item>
              </el-col>
             </el-row>
          </div>
        </div>
      </el-card>

      <el-input  v-model="form.examid" type='hidden'></el-input>
      </el-form>
      <!-- <el-form-item> -->
        <el-button  type="primary" :disabled="issubmit || detail.seat_generat_status != 0" @click.native="onSubmit('form')">保存</el-button>
      <!-- </el-form-item> -->

  </div>
</template>

<script>
import { validUrl } from '@/utils/validate'
import { pointList } from '@/api/kaowu/point'
import { examTopicAdd,examTopicList,examInfoDetail } from '@/api/kaowu/exam'
import { topicList } from '@/api/kaowu/topic'
import apiArr from '@/kaowu_api'
import { getToken } from '@/utils/auth'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { Editor, Toolbar },
  name: 'examTopic',
  props: ['kkki_id','examid'],
  data() {
    var validateContent = (rule, value, callback) => {
      value = this.editor.getText()
      if (value === '') {
        callback(new Error('请输入内容'))
      } else {
        callback()
      }
    }
    var validateUrl = (rule, value, callback) => {
      if (value == '') {
        callback()
      }
      if (!validUrl(value)) {
        callback(new Error('请输入正确的网址'))
      } else {
        callback()
      }
    }
    return {
      detail:{
        seat_generat_status:0
      },
      issubmit: false,
      editor: null,
      toolbarConfig: {
        excludeKeys: [
          'fullScreen'
        ]
      },
      headers: { admintoken: getToken() },
      fileupload_size: '',
      fileupload_ext: '',
      apiUpload: window.global.RequestBaseUrl + apiArr.upload,
      apiAttachUpload: window.global.RequestBaseUrl + apiArr.uploadAttach,
      roomList: [],
      pointList:[],
      imageUrl: '',
      form: {
        topicinfo: [
          {id:null,changci:'1',list:[
            {name:'',date:null,start_time:null,end_time:null,people:0}
          ]}
        ],
        examid:null,
        kkki_id:null,

      }



    };
  },
  computed: {
    config() {
      return this.$store.state.config
    }
  },
  mounted() {
  },
  created() {
    this.fileupload_size = this.config.fileupload_size
    this.fileupload_ext = this.config.fileupload_ext
    this.fetchCategoryData()
    // this.init()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    init(){
      examInfoDetail({id:this.kkk_id}).then((res)=>{
        console.log('******************78798')
        this.detail = res.data.info
      })
    },


    fun_change_source(val) {
      if (val === '0') {
        this.form.source_reprint = ''
      }
    },
    insertTopic(){
      this.form.topicinfo.push({id:null,changci:'1',list:[
            {name:'',date:null,start_time:null,end_time:null,people:0}
          ]})
    },
    // 删除按钮
    delTopic(index) {
      console.log(index)
       this.form.topicinfo.splice(index,1)
    },
    insertChangci(index){
      this.form.topicinfo[index].list.push({name:'',date:null,start_time:null,end_time:null})
    },

    delChangci(index,sub_index){
      this.form.topicinfo[index].list.splice(sub_index,1)
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      this.editor.getMenuConfig('uploadImage').headers = {
        admintoken: getToken()
      }
      this.editor.getMenuConfig('uploadImage').withCredentials = true
      this.editor.getMenuConfig('uploadImage').server = window.global.RequestBaseUrl + apiArr.uploadEditor
      this.editor.getMenuConfig('uploadVideo').headers = {
        admintoken: getToken()
      }
      this.editor.getMenuConfig('uploadVideo').withCredentials = true
      this.editor.getMenuConfig('uploadVideo').server = window.global.RequestBaseUrl + apiArr.uploadEditorVideo
    },


    fetchCategoryData() {
      // pointList().then(response=>{this.pointList = response.data.items})

      topicList().then(response => {this.topicList = response.data.items}).finally(()=>{
        examTopicList({kkki_id:this.kkki_id}).then(response=>{
          this.form.topicinfo = response.data.topicinfo
          console.log(this.form.roominfo)
        })
      })


    },
    onSubmit(formName) {
      const that = this
      that.issubmit = true
      that.form.examid = that.examid
      that.form.kkki_id = that.kkki_id
      const insertData = { ...this.form }
      console.log(insertData)
      // return ;
      examTopicAdd(insertData)
        .then(response => {
          this.$message.success(response.message)
          that.issubmit = false
          return true
        })
        .catch(() => {
          that.issubmit = false
          return false
        })
    },
    handleThumbSuccess(res, file) {
      if (res.code == 200) {
        this.imageUrl = URL.createObjectURL(file.raw)
        this.form.thumb = res.data.file_id
      } else {
        this.$message.error(res.message)
        return false
      }
    },
    beforeThumbUpload(file) {
      const filetypeArr = file.type.split('/')
      const filetype = filetypeArr[1]
      const configFileExtArr = this.fileupload_ext.split(',')

      if (!configFileExtArr.includes(filetype)) {
        this.$message.error('上传文件格式不允许')
        return false
      }
      if (file.size / 1024 > this.fileupload_size) {
        this.$message.error(`上传文件最大为${this.fileupload_size}kb`)
        return false
      }
      return true
    },
    goto(target) {
      this.$router.push(target)
    }
  }
}
</script>
<style scoped>
  .changci{
    border:1px solid #efefef;
    padding:10px;
    margin-bottom:30px;
    width:80%;
    position:relative;
  }
  .changci-del{
    position:absolute;
    background-color: red;
    top:-10px;
    right:0;
  }
.thumb-uploader {
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 122px;
  height: 122px;
}
.thumb-uploader img {
  width: 120px;
  height: 120px;
  border-radius: 6px;
}
.thumb-uploader:hover {
  border-color: #409eff;
}
.thumb-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.el-textarea,.el-select,.el-input,
.el-date-editor {
  width: 100%;
}
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 80%;
    margin-bottom:50px;
    /* height:500px; */
    overflow: auto;
  }
</style>
